package com.apesay.agent;

import javassist.*;

/**
 * ClassName:JavassistStar
 * Reason:	 
 * Date:     2017/11/8 18:06
 *
 * @author sid
 */
public class JavassistStar {
    
    private static void codeBytesPlus(String beanName,String methodName){

        ClassPool classPool = ClassPool.getDefault();
        try {
            CtClass ctClass = classPool.get(beanName);

            // 获取指定方法名称  
            CtMethod method = ctClass.getDeclaredMethod(methodName, null);
            // 赋值方法到新方法中  
            CtMethod newMethod = CtNewMethod.copy(method, ctClass, null);
            // 修改源方法名称  
            String oldName = method.getName() + "$Impl";
            method.setName(oldName);
            // 修改原方法  
            newMethod.setBody("{" +
                    "System.out.println(\"doBefor-------执行前\");" +
                    ""+oldName+"($$);" +
                    "System.out.println(\"doAfter-------执行后\");" +
                    "}");
            // 将新方法添加到类中  
            ctClass.addMethod(newMethod);
            // 加载重新编译的类  
            ctClass.toClass();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        codeBytesPlus("com.apesay.agent.UserAgent","hello");
        
        UserAgent userAgent = new UserAgent();
        userAgent.hello();

        System.out.println("java_passport_porvider_info_1111111111".getBytes().length);
    }
    
}
